package com.kensure.shike.user.service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import co.kensure.exception.BusinessExceptionUtil;
import co.kensure.frame.JSBaseService;
import co.kensure.mem.CollectionUtils;
import co.kensure.mem.MapUtils;

import com.kensure.basekey.BaseKeyService;
import com.kensure.shike.user.dao.SKUserAddrDao;
import com.kensure.shike.user.model.SKUserAddr;

/**
 * 用户地址服务实现类
 * 
 * @author fankd created on 2019-6-12
 * @since
 */
@Service
public class SKUserAddrService extends JSBaseService {

	@Resource
	private SKUserAddrDao dao;
	@Resource
	private BaseKeyService baseKeyService;

	public SKUserAddr selectOne(Long id) {
		return dao.selectOne(id);
	}

	public List<SKUserAddr> selectByIds(Collection<Long> ids) {
		return dao.selectByIds(ids);
	}

	public List<SKUserAddr> selectAll() {
		return dao.selectAll();
	}

	public List<SKUserAddr> selectByWhere(Map<String, Object> parameters) {
		return dao.selectByWhere(parameters);
	}

	public long selectCount() {
		return dao.selectCount();
	}

	public long selectCountByWhere(Map<String, Object> parameters) {
		return dao.selectCountByWhere(parameters);
	}

	public boolean insert(SKUserAddr obj) {
		super.beforeInsert(obj);
		obj.setId(baseKeyService.getKey("sk_user_addr"));
		return dao.insert(obj);
	}

	public boolean update(SKUserAddr obj) {
		super.beforeUpdate(obj);
		return dao.update(obj);
	}

	public boolean updateByMap(Map<String, Object> params) {
		return dao.updateByMap(params);
	}

	public boolean delete(Long id) {
		return dao.delete(id);
	}

	public boolean deleteMulti(Collection<Long> ids) {
		return dao.deleteMulti(ids);
	}

	public boolean deleteByWhere(Map<String, Object> parameters) {
		return dao.deleteByWhere(parameters);
	}

	/**
	 * 根据userid拿到用户登录信息
	 * 
	 * @return
	 */
	public List<SKUserAddr> selectByUserId(Long userid) {
		Map<String, Object> parameters = MapUtils.genMap("userid", userid);
		List<SKUserAddr> loginlist = selectByWhere(parameters);
		return loginlist;
	}
	
	
	/**
	 * 用户地址保存
	 * 
	 * @return
	 */
	public void save(Long userid,SKUserAddr addr) {
		if(userid == null){
			BusinessExceptionUtil.threwException("用户不能为空");
		}
		List<SKUserAddr> loginlist = selectByUserId(userid);
		addr.setUserid(userid);
		if(CollectionUtils.isEmpty(loginlist)){
			addr.setIsmoren(1);
		}
		if(addr.getIsmoren() == null){
			addr.setIsmoren(0);
		}
		
		if(addr.getIsmoren() == 1){
			if(CollectionUtils.isNotEmpty(loginlist)){
				for(SKUserAddr temp:loginlist){
					if(temp.getIsmoren() == 1){
						temp.setIsmoren(0);
						update(temp);
					}
				}
			}		
		}
		if(addr.getId() == null){
			insert(addr);
		}else{
			update(addr);
		}
	}

}
